import { loadResources, loadImg, loadFollow, parseTopic, get } from "@/utils/haijiao"

export default defineBackground(() => {
    browser.runtime.onInstalled.addListener(({ reason }) => {
        if (['install', 'update'].includes(reason)) {
            browser.contextMenus?.create({
                id: 'haijiao-sidePanel',
                title: 'haijiao-sidePanel',
                contexts: ['all']
            });
        }
    });
    browser.contextMenus?.onClicked.addListener((info, tab) => {
        if (info.menuItemId === 'haijiao-sidePanel') {
            // 配置sidePanel路径,使点击图标打开sidePanel生效
            browser.sidePanel.setOptions({ path: browser.runtime.getURL("/sidepanel1.html") });
            browser.sidePanel.open({ windowId: tab.windowId });
            // 使点击图标打开sidePanel失效
            browser.sidePanel.setPanelBehavior({ openPanelOnActionClick: false }).catch((error) => console.error(error));
        }
    })
    // browser.sidePanel.setOptions({ path: browser.runtime.getURL("/sidepanel.html") });
    // browser.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }).catch((error) => console.error(error));
    browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
        console.log(message)
        if (message.action === 'openTabWithImages') {
            if (!message.items) return
            browser.tabs.create({ url: browser.runtime.getURL("/images.html"), active: false }).then(tab => {
                browser.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {
                    if (tabId === tab.id && changeInfo.status === 'complete') {
                        // 发送消息到新标签页
                        //   browser.tabs.sendMessage(tab.id, { action: 'messageFromBackground', data: message.data });
                        browser.tabs.sendMessage(tab.id, { action: 'openTabWithImages1', items: message.items })

                        // 移除监听器，避免重复发送消息
                        browser.tabs.onUpdated.removeListener(listener);
                    }
                })
            }).then(sendResponse)
        }
        if (message.action === 'openTabWithUrl') {
            if (!message.url) return
            browser.tabs.create({ url: message.url, active: false }).then(tab => {
                browser.tabs.onUpdated.addListener(async function listener(tabId, changeInfo) {
                    if (tabId === tab.id && changeInfo.status === 'complete') {
                        await sendResponse("ok")
                        // 移除监听器，避免重复发送消息
                        browser.tabs.onUpdated.removeListener(listener);
                    }
                })
            }).then(sendResponse)
        }
        if (message.action === 'imageUrl') {
            loadImg(message.items).then(items => {
                return { items }
            }).then(sendResponse)
            return true;
        }
        if (message.action === 'attachments') {
            // loadResources(message.topicId).then(sendResponse)
            parseTopic(message.topicId).then((data: any)=>{
                return {attachments: data?.attachments}
            }).then(sendResponse)
            .catch(error => {
                sendResponse({error})
            })
            return true;
        }

        if (message.action === 'follow') {
            loadFollow(`https://haijiao.com/api/user/favorite/users`, message.info.token, message.info.uid)
                .then(sendResponse)
                .catch(error => {
                    sendResponse({error})
                })
            return true;
        }
        if (message.action === 'topic') {
            parseTopic(message.topicId).then((data: any)=>{
                return {topic: data}
            }).then(sendResponse)
            .catch(error => {
                sendResponse({error})
            })
            return true;
        }
        if (message.action === 'topics') {
            // loadTopics(`https://haijiao.com/api/topic/node/topics`, message.params).then(sendResponse)
            get(`https://haijiao.com/api/topic/node/topics`, message.params).then(data=>{
                return {topics: data}
            }).then(sendResponse)
            .catch(error => {
                sendResponse({error})
            })
            return true;
        }
        if (message.action === 'search') {
            get(`https://haijiao.com/api/topic/searchV2`, message.params).then(data=>{
                return {topics: data}
            }).then(sendResponse)
            .catch(error => {
                sendResponse({error})
            })
            // loadTopics(`https://haijiao.com/api/topic/searchV2`, message.params).then(sendResponse)
            return true;
        }
    })
});